package com.zhdl.hardware.plc.siemens_tcpip.repository.impl;

import com.google.common.eventbus.Subscribe;
import com.project.command.faq.event.behavior.BehaviorPerform;
import com.zhdl.common.ytools.callback.CommonCallback;
import com.zhdl.common.ytools.eventbus.center.EventBusCenter;
import com.zhdl.hardware.plc.siemens_tcpip.entity.SiemensReceiveData;
import com.zhdl.hardware.plc.siemens_tcpip.repository.SiemensTcpCmdHandleDao;
import com.zhdl.network.strategy.common.ProtocolContext;
import com.zhdl.network.strategy.modbustcp.ModbusTcpStrategy;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class SiemensTcpCmdHandleDaoImpl implements SiemensTcpCmdHandleDao {

    /**
     * PLC西门子-网口
     */
    public String port;
    /**
     * 通信协议处理
     */
    public ProtocolContext protocolContext;
    /**
     * Callback 回调管理
     */
    public Map<String, CommonCallback<String>> commonCallbackMap = new ConcurrentHashMap<>();
    private final List<CommonCallback<String>> callback = new Vector<>();


    /**
     * 添加一个网口
     *
     * @param port            IP
     * @param behaviorPerform 发送
     */
    public SiemensTcpCmdHandleDaoImpl(String port, BehaviorPerform behaviorPerform) {
        EventBusCenter.getEventBus().register(this);
        protocolContext = new ProtocolContext(new ModbusTcpStrategy(port, behaviorPerform));
        this.port = port;
    }

    /**
     * EventBus获取plc传入的信息
     *
     * @param event eventBus接收PLC信息
     */
    @Subscribe
    public void dataReception(SiemensReceiveData event) {
        log.info("plc 读取到的所有数据为 ->{}", event.getData_all());
        for (CommonCallback<String> stringCommonCallback : callback) {
            stringCommonCallback.statusCallback(event.getData_all());
        }
    }

    /**
     * 读取PLC全部数据
     *
     * @param callback 回调
     */
    @Override
    public void readSiemensTcpIPDate(CommonCallback<String> callback) {
        this.callback.add(callback);
    }

}
